package com.taptech.doufu.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taptech.doufu.bean.personalcenter.PersonalCardInfo;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.view.TTHomeViewPager;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.weex.image.TFImageViewUtil;
import com.taptech.doufu.ui.fragment.CommonCpFragment;
import com.taptech.doufu.ui.fragment.NewMyCpFragment;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.weex.StartWeexActivityUtils;
import com.taptech.doufu.ui.adapter.ScrollAbleViewPagerAdapter;
import com.taptech.doufu.bean.UserBean;
import com.taptech.doufu.bean.UserBean2;
import com.taptech.doufu.bean.UserWorksBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.ui.view.PersonalTabViewGroup;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.ui.view.ScrollableLayout;
import com.taptech.doufu.ui.fragment.ScrollAbleFragment;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.viewpager.widget.ViewPager;

/**
 * 他人的个人中心
 *
 * @author zhanghao
 */
public class NewOthersPersonalActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener
{

    private ScrollableLayout mScrollLayout;
    private String userId;
    private WaitDialog dialog;
    private String user_nickName;
    private UserBean2 mUserBean;
    private Activity mActivity;
    // 所有点击可跳转UI
    private LinearLayout mPersonalInfoBtn;
    private ImageView mMorePersonalInfoBtn;
    private LinearLayout mPersonalFollowBtn;
    private LinearLayout mPersonalMessageBtn;
    private LinearLayout mPersonalFollowNumBtn;
    private LinearLayout mPersonalFansNumBtn;
    private LinearLayout mPersonalMessageNumBtn;
    // 所有显示UI
    private ImageView mPersonalHeadLayout;
    private TextView mNickName;
    private TextView mUserSignature;
    private ImageView mUserHeadImg;
    private TextView mPersonalFollowCount;
    private TextView mPersonalFansCount;
    private TextView mPersonalActivityCount;
    private TextView mPersonalFollowText;
    private boolean hasBeenFollowed = false;
    private ImageView mFollowBtn;
    private TextView personMessageTextView;
    private TextView tvLevel,tvVip;
    private ImageView ivLevel,ivVip;

    // 举报按钮
    private TextView mReportBtn;
    private ImageView no_content_img;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_personal);
        initHeadView();
        initDate();
    }

    private void initDate()
    {
        mActivity = NewOthersPersonalActivity.this;
        userId = getIntent().getStringExtra(Constant.UID);
        user_nickName = getIntent().getStringExtra(Constant.USERNICKNAME);
        dialog = new WaitDialog(this, R.style.updateDialog);
        dialog.show();
        if (user_nickName != null && user_nickName.trim().length() > 0)
        {
            PersonalInfoService.getInstance().getUserWorksRequest(this, null ,user_nickName);
            PersonalInfoService.loadPersonalCenterContent_by_userNickName(this, user_nickName);
        } else if (userId != null)
        {
            PersonalInfoService.getInstance().getUserWorksRequest(this, userId);
            PersonalInfoService.loadPersonalCenterContent(this, userId);
        }
    }

    private void initHeadView()
    {
        tvLevel = (TextView) findViewById(R.id.tvLevel);
        tvVip = (TextView) findViewById(R.id.tvVip);
        ivLevel = (ImageView) findViewById(R.id.ivLevel);
        ivVip = (ImageView) findViewById(R.id.ivVip);
        no_content_img = (ImageView) findViewById(R.id.no_content_img);
        mPersonalHeadLayout = (ImageView) findViewById(R.id.other_personal_center_head_layout);
        mPersonalInfoBtn = (LinearLayout) findViewById(R.id.personal_info_enter);
        mPersonalInfoBtn.setOnClickListener(this);
        mMorePersonalInfoBtn = (ImageView) findViewById(R.id.more_personal_info_btn);
        mMorePersonalInfoBtn.setImageResource(R.drawable.back);
        mMorePersonalInfoBtn.setOnClickListener(this);
        mPersonalFollowBtn = (LinearLayout) findViewById(R.id.personal_follow_btn);
        mPersonalFollowBtn.setOnClickListener(this);
        mPersonalMessageBtn = (LinearLayout) findViewById(R.id.personal_message_btn);
        mPersonalMessageBtn.setOnClickListener(this);
        mPersonalFollowNumBtn = (LinearLayout) findViewById(R.id.personal_follow_num_btn);
        mPersonalFollowNumBtn.setOnClickListener(this);
        mPersonalFansNumBtn = (LinearLayout) findViewById(R.id.personal_fans_num_btn);
        mPersonalFansNumBtn.setOnClickListener(this);
        mPersonalMessageNumBtn = (LinearLayout) findViewById(R.id.personal_message_num_btn);
        mPersonalMessageNumBtn.setOnClickListener(this);
        // 头像
        mUserHeadImg = (ImageView) findViewById(R.id.personal_activity_other_dynamic_user_portrait);
        // 昵称
        mNickName = (TextView) findViewById(R.id.nick_name);
        // 个性签名
        mUserSignature = (TextView) findViewById(R.id.user_signature);
        // 关注/粉丝/动态
        mPersonalFollowCount = (TextView) findViewById(R.id.personal_follow_count);
        mPersonalFansCount = (TextView) findViewById(R.id.personal_fans_count);
        mPersonalActivityCount = (TextView) findViewById(R.id.personal_activity_count);
        // 关注按钮的文字
        mPersonalFollowText = (TextView) findViewById(R.id.follow_button_textview);
        mFollowBtn = (ImageView) findViewById(R.id.follow_img);
        personMessageTextView = (TextView) findViewById(R.id.private_message_button_textview);
        // 举报按钮
        mReportBtn = (TextView) findViewById(R.id.user_report_btn);
        mReportBtn.setOnClickListener(this);

    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {
        if (dialog != null && dialog.isShowing())
        {
            dialog.dismiss();
        }
        if (response == null)
        {
            return;
        }
        if (response.getStatus() == 0)
        {
            // 获取个人中心的内容列表信息
            switch (handleType)
            {
                case PersonalInfoService.HANDLE_TYPE_LOAD_PERSONAL_CENTER_CONTENT:
                {
                    JSONObject json = (JSONObject) response.getData();
                    try
                    {
                        UserBean2 userBean2 = new UserBean2();
                        userBean2.setJson2(json.getJSONObject("user"));
                        if (userBean2 != null)
                        {
                            setUserInfo(userBean2);
                        } else
                        {
                            UIUtil.toastMessage(mActivity, response.getUser_msg());
                        }
                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                    // 显示用户内容信息
                    break;
                }
                case PersonalInfoService.HANDLE_HAS_WORKS:
                    JSONObject data = (JSONObject) response.getData();
                    UserWorksBean userWorksBean = new UserWorksBean();
                    userWorksBean.setJson2(data);
                    initUpView(userWorksBean);
                    break;
                default:
                    break;
            }
        } else
        {
            UIUtil.toastMessage(this, "网络异常，请检查网络后再试");
        }
    }

    private PersonalTabViewGroup mTabView;
    private List<ScrollAbleFragment> mSweepListViews;
    private TTHomeViewPager mViewPager;
    private ScrollAbleViewPagerAdapter viewPagerAdapter;

    protected void initUpView(UserWorksBean userWorksBean)
    {
        if (userWorksBean == null)
        {
            return;
        }
        UserBean userBean = userWorksBean.getUser();
        if (userBean != null){
            userId = userBean.getUserId();
            if (userBean.getLevel() > 0) {
                tvLevel.setText("豆花 Lv."+userBean.getLevel());
                GlideUtil.displayImage(ivLevel,userBean.getLevel_icon());
                tvLevel.setVisibility(View.VISIBLE);
                ivLevel.setVisibility(View.VISIBLE);
            }else{
                tvLevel.setVisibility(View.GONE);
                ivLevel.setVisibility(View.GONE);
            }
            tvVip.setVisibility(View.VISIBLE);
            ivVip.setVisibility(View.VISIBLE);
            if (userBean.getIs_year_vip() > 0) {
                ivVip.setImageResource(R.drawable.icon_year_vip);
                tvVip.setText("年度会员");
            } else if (userBean.getIs_vip() > 0) {
                ivVip.setImageResource(R.drawable.icon_normal_vip);
                tvVip.setText("会员");
            }else{
                tvVip.setVisibility(View.GONE);
                ivVip.setVisibility(View.GONE);
            }
        }


        mScrollLayout = (ScrollableLayout) findViewById(R.id.scrollableLayout);
        mTabView = (PersonalTabViewGroup) findViewById(R.id.top_tab_view);
        mViewPager = (TTHomeViewPager) findViewById(R.id.sweep_view_pager);
        mViewPager.setOffscreenPageLimit(6);
        mSweepListViews = new ArrayList<ScrollAbleFragment>();
        List<String> name_lists = new ArrayList<String>();
        if (Integer.parseInt(userWorksBean.getNovel_count()) > 0)
        {
            name_lists.add("小说");
            mSweepListViews.add(CommonCpFragment.newInstance(CommonCpFragment.TYPE_PERSONAL_NOVEL, userId));
        }

        if (Integer.parseInt(userWorksBean.getDrawing_count()) > 0)
        {
            name_lists.add("绘画");
            mSweepListViews.add(CommonCpFragment.newInstance(CommonCpFragment.TYPE_PERSONAL_DRAW, userId));
        }
        if (Integer.parseInt(userWorksBean.getJournal_count()) > 0)
        {
            name_lists.add("帖子");
            mSweepListViews.add(CommonCpFragment.newInstance(NewMyCpFragment.TYPE_PERSONAL_PUBLISHED_NOTE, userId));
        }
        if (Integer.parseInt(userWorksBean.getNovel_review_count()) > 0)
        {
            name_lists.add("文评");

            mSweepListViews.add(CommonCpFragment.newInstance(NewMyCpFragment.TYPE_PERSONAL_PUBLISHED_SWEEP, userId));
        }
        if (mSweepListViews.size() == 0)
        {
            no_content_img.setVisibility(View.VISIBLE);
            return;
        }
        String[] NAMESTRING = (String[]) name_lists.toArray(new String[name_lists.size()]);
        mTabView.putStringsTabs(NAMESTRING);
        mTabView.setChoosePageListener(new PersonalTabViewGroup.ChoosePage()
        {
            @Override
            public void updatePage(int position)
            {
                mViewPager.setCurrentItem(position, true);
            }
        });
        viewPagerAdapter = new ScrollAbleViewPagerAdapter(getSupportFragmentManager(), mSweepListViews);
        mViewPager.setAdapter(viewPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {

            @Override
            public void onPageSelected(int arg0)
            {
                // TODO Auto-generated method stub
                mTabView.moveTopStripTo(arg0);
                mScrollLayout.getHelper().setCurrentScrollableContainer(mSweepListViews.get(arg0));
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2)
            {
                // TODO Auto-generated method stub
            }

            @Override
            public void onPageScrollStateChanged(int arg0)
            {
                // TODO Auto-generated method stub
            }

        });
        if (mSweepListViews.size() > 0)
        {
            mScrollLayout.getHelper().setCurrentScrollableContainer(mSweepListViews.get(0));
        }
    }

    public void setUserInfo(UserBean2 userBean)
    {
        this.mUserBean = userBean;
        try
        {
            this.userId = userBean.getUid();
            // 粉小二粉丝数显示特殊处理
            if (userId.equals("50100")||userId.equals("50102"))
            {
                mPersonalFansCount.setText("∞");
            } else
            {
                mPersonalFansCount.setText(userBean.getFans_counts());
            }
            // 管理员私信变反馈
            if (Constant.managerIdSet.contains(userId))
            {
                personMessageTextView.setText("反馈");
            } else
            {
                personMessageTextView.setText("私信");
            }
            mNickName.setText(userBean.getNickname());
            if (!TextUtil.isEmpty(userBean.getUser_signature())) {
                mUserSignature.setVisibility(View.VISIBLE);
            }else{
                mUserSignature.setVisibility(View.GONE);
            }
            mUserSignature.setText(userBean.getUser_signature());

            GlideUtil.displayCircleImageBorder(mUserHeadImg, userBean.getHead_image(),2,getResources().getColor(R.color.border_color_1));
            TFImageViewUtil.showVagueImage(mPersonalHeadLayout,userBean.getHead_image(),8);

            mPersonalFollowCount.setText(userBean.getAttentions_counts());

            mPersonalActivityCount.setText(userBean.getActivity_count());
            // 关注按钮
            if (userBean.getFollowing() != null)
            {
                if (userBean.getFollowing().equals("1"))
                {
                    mPersonalFollowText.setText("已关注");
                    mFollowBtn.setImageResource(R.drawable.followed_btn_draw);
                    hasBeenFollowed = true;
                } else if (userBean.getFollowing().equals("0"))
                {
                    mPersonalFollowText.setText("关注");
                    mFollowBtn.setImageResource(R.drawable.follow_btn_draw);
                    hasBeenFollowed = false;
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.personal_info_enter: {
                break;
            }
            // 详情页
            case R.id.more_personal_info_btn:
            {
                finish();
                break;
            }
            case R.id.personal_follow_btn:
            {
                if (hasBeenFollowed == false)
                {
                    // mPersonalFollowText.setText("已关注");
                    // mFollowBtn.setImageResource(R.drawable.followed_btn_draw);
                    hasBeenFollowed = true;
                } else
                {

                }
                addAttention();
                break;
            }
            case R.id.personal_message_btn:
            {
                sendMessage();
                break;
            }
            case R.id.personal_follow_num_btn:
            {
                Intent intent = new Intent(mActivity, PersonalAttentionsActivity.class);
                intent.putExtra(Constant.UID, userId);
                mActivity.startActivity(intent);
                break;
            }
            case R.id.personal_fans_num_btn:
            {
                if (mUserBean != null)
                {
                    // 腐小二的粉丝数不能点击
                    if (userId.equals("50100"))
                    {
                        ;
                    } else
                    {
                        Intent intent = new Intent(mActivity, PersonalFansActivity.class);
                        intent.putExtra(Constant.UID, userId);
                        mActivity.startActivity(intent);
                    }
                }

                break;
            }
            case R.id.personal_message_num_btn:
            {
                if (!TextUtils.isEmpty(userId)) {
                    Intent intent = new Intent(mActivity, PersonalNewDynamicActivity.class);
                    intent.putExtra(Constant.UID, userId);
                    if (mUserBean != null) {
                        intent.putExtra(Constant.USER_HEAD_IMG, mUserBean.getUser_head_img());
                    }
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mActivity.startActivity(intent);
                }
                break;
            }
            case R.id.user_report_btn:
                if (mUserBean != null)
                {
                    HomeMainServices.getInstance().reportContentRequest(mActivity, userId, String.valueOf(Constant.CONTENT_TYPE_USER), userId);
                }

                break;
            default:
                break;
        }

    }

    private void sendMessage()
    {
        if (mUserBean == null)
        {
            return;
        }
        if (AccountService.getInstance().isLogin())
        {

            if (Constant.managerIdSet.contains(userId))
            {
                Intent intent = new Intent(mActivity, BrowseActivity.class);
                intent.putExtra(Constant.URL, "http://api.doufu.la/index.php/help/question");
                intent.putExtra(Constant.TITLE, "");
                mActivity.startActivity(intent);
            } else {
                StartWeexActivityUtils.startPrivateMsgActivity(mActivity,userId,
                        mUserBean.getNickname());
            }
        } else
        {
            AccountService.getInstance().jumpToLogin();
        }

    }

    public void addAttention()
    {
        if (mUserBean == null)
        {
            return;
        }
        if (AccountService.getInstance().isLogin())
        {
            if (mUserBean.getFollowing() == null)
            {
                return;
            }

            if (mUserBean.getFollowing().equals("1"))
            {
                UIUtil.showEnsureDialog(mActivity, "确定取消关注？", new UIUtil.EnsureListener()
                {
                    @Override
                    public void sure()
                    {
                        PersonalInfoService.getInstance().cancelAttention(userId, new HttpResponseListener()
                        {

                            @Override
                            public void handleResponse(int handleType, HttpResponseObject response)
                            {
                                if (response.getStatus() == 0)
                                {
                                    UIUtil.toastMessage(mActivity, "不能做朋友了");
                                    PersonalInfoService.getInstance().delMyAttentions(userId);
                                    mUserBean.setFollowing("0");
                                    mPersonalFollowText.setText("关注");
                                    mFollowBtn.setImageResource(R.drawable.follow_btn_draw);
                                    hasBeenFollowed = false;

                                } else
                                {
                                    UIUtil.toastMessage(mActivity, "取消关注失败");
                                }

                            }
                        }, mActivity);

                    }

                    @Override
                    public void cancel()
                    {

                    }
                });

            } else
            {

                PersonalInfoService.getInstance().addAttention(userId, new HttpResponseListener()
                {

                    @Override
                    public void handleResponse(int handleType, HttpResponseObject response)
                    {
                        if (response.getStatus() == 0)
                        {

                            if (mUserBean != null)
                            {
                                PersonalInfoService.getInstance().addMyAttentions(getPersonalCardInfo(mUserBean));
                            }
                            Log.d("tag", "关注列表长度为===========" + PersonalInfoService.getInstance().getAttentions().size());

                            UIUtil.toastMessage(mActivity, "关注成“攻”");
                            mPersonalFollowText.setText("已关注");
                            mFollowBtn.setImageResource(R.drawable.followed_btn_draw);
                            mUserBean.setFollowing("1");

                        } else
                        {
                            UIUtil.toastMessage(mActivity, "添加关注失败");
                        }

                    }
                }, mActivity);

            }
        } else
        {
            AccountService.getInstance().jumpToLogin();
        }
    }


    private PersonalCardInfo getPersonalCardInfo(UserBean2 userBean){
        PersonalCardInfo bean = new PersonalCardInfo();
        bean.setUid(userBean.getUid());
        bean.setNickname(userBean.getNickname());
        bean.setHead_image(userBean.getHead_image());
        bean.setUser_signature(userBean.getUser_signature());
        bean.setSocial_nickname(userBean.getNickname());
        bean.setUser_head_img(userBean.getUser_head_img());
        bean.setArticle_counts(userBean.getArticle_counts());
        bean.setFans_counts(userBean.getFans_counts());
        bean.setComment_times(userBean.getComment_times());
        bean.setCollect_counts(userBean.getCollect_counts());
        bean.setArticle_counts(userBean.getArticle_counts());
        bean.setMedal(userBean.getMedal());
        bean.setType(userBean.getType());
        bean.setFollowing(userBean.getFollowing());
        bean.setActivity_num(userBean.getActivity_num());
        bean.setCompex_score(userBean.getCompex_score());
        return bean;
    }

    public static void startActivity(Context context,String uid){
        Intent intent = new Intent(context, NewOthersPersonalActivity.class);
        intent.putExtra(Constant.UID, uid);
        context.startActivity(intent);
    }

}
